char a[102][103];r[9999],s[9999];main(n,m,i,j,x,y,e,w,t,l)
{
	for(gets(&n);~scanf("%d%d\n",&n,&m);printf("%d\n",e?e+1:-1))
	{
		memset(*a,'#',m+2),a[0][m+2]=0;
		for(i=1;i<=n;i++)
		{
			*a[i]='#';
			gets(a[i]+1);
			strcpy(a[i]+strlen(a[i]),"#");
			if(j=strchr(a[i],'S'))x=a[i],x=j-x,y=i;
		}
		memset(a[n+1],'#',m+2),a[n+1][m+2]=0;

		*r=x;r[1]=y;
		for(w=t=e=l=0;!e;l++,t=0)
		{
			while(~w)
			{
				x=r[2*w],y=r[2*w--+1];
				a[y][x]='#';

				if(a[y][x+1]=='E'||a[y][x-1]=='E'||a[y+1][x]=='E'||a[y-1][x]=='E')e=l;
				if(a[y][x+1]-'#')s[t*2]=x+1,s[t++*2+1]=y,a[y][x+1]='#';
				if(a[y][x-1]-'#')s[t*2]=x-1,s[t++*2+1]=y,a[y][x-1]='#';
				if(a[y+1][x]-'#')s[t*2]=x,s[t++*2+1]=y+1,a[y+1][x]='#';
				if(a[y-1][x]-'#')s[t*2]=x,s[t++*2+1]=y-1,a[y-1][x]='#';
			}
			w=t-1;
	
			if(!t)
				break;

			memcpy(r,s,8*t);
		}
	}
}
